from datetime import timedelta
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _
from google.appengine.api import users
from looptube.models import VideoInfo, RadioLog
from looptube.utils import fetchYouTubeVideoData
from . import commonInit

def init(request):
    # init from commonInit()
    resp = commonInit(request)
    if (HttpResponse == resp.__class__):
        return resp     # commonInit() returned HttpResponse
    contextDict = resp  # commonInit() returned dict
            
    return contextDict

# actions
def errorAction(request, videoID):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (videoID):
        videoResult = fetchYouTubeVideoData(videoID)
        if (len(videoResult) == 0):
            videoFound = False
        else:
            videoFound = True
    else:
        videoFound = False

    contextDict['videoFound'] = videoFound
    contextDict['pageTitle'] = _('Unable to loop this video')
    contextDict['videoID'] = videoID
    return render_to_response('looperror.html', contextDict)

def loopAction(request, movieID, source='', noshare=False, forceLogin=False):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict
    
    if (request.GET.__contains__('forceLogin') and (request.GET['forceLogin']) and (not forceLogin)):
        forceLogin = True

    user = users.get_current_user()
    if ((forceLogin) and (None == user)):
        return HttpResponseRedirect(contextDict['loginURL'])

    if ('' == source):
        return HttpResponseRedirect('/loop/youtube/'+movieID)
    
    if ((source not in ['youtube']) or ('' == movieID)):
        return HttpResponseRedirect('/');

    videoInfo = VideoInfo.getVideoInfo(source, movieID, noshare)
    if (None == videoInfo):
        return HttpResponseRedirect('/loop/error/'+movieID)
    
    contextDict['pageTitle'] = _('Now looping') + ': ' + unicode(videoInfo.title)
    contextDict['videoInfo'] = videoInfo
    if (videoInfo.duration):
        contextDict['videoDuration'] = unicode(timedelta(0, 0, 0, 0, videoInfo.duration))[:-3]
    else:
        contextDict['videoDuration'] = _('N/A')
    contextDict['loopMovieID'] = movieID
    contextDict['loopMovieURL'] = 'http://www.youtube.com/watch?v=' + movieID
    contextDict['actionSidebar'] = 'sidebar/loopVideoAction.html'
    return render_to_response('loop.html', contextDict)
